/*
 * Copyright 2003-2007 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

package com.colony.networkvm.instruction;

import java.io.IOException;

import com.argot.TypeException;
import com.argot.TypeInputStream;
import com.argot.TypeOutputStream;
import com.argot.TypeReader;
import com.argot.TypeWriter;
import com.colony.IColonyClient;
import com.colony.networkvm.NvmClient;
import com.colony.networkvm.machine.NvmInstance;
import com.colony.remote.RemoteException;

public class NvmToHostInstruction
implements NvmInstruction
{
	public static final String TYPENAME = "nvm.instruction.to_host";

    public void execute(NvmInstance request) 
    throws RemoteException
    {
        request.incProgramCounter();
        
        String host = (String) request.pop();
        
        // This will return after the host finishes processing.
        IColonyClient client = request.getEnvironment().getClient( host );
        if ( client == null )
        {
        	throw new RemoteException( "host not available: "+ host );
        }
        
        if ( !(client instanceof NvmClient))
        {
        	throw new RemoteException( "host not Nvm capable:" + host );
        }
    	NvmClient nvmClient = (NvmClient) client;
    	nvmClient.sendToHost( request );
    }

    public static class NvmToHostInstructionTypeWriter
    implements TypeWriter
    {
	    public void write(TypeOutputStream out, Object o) throws TypeException, IOException
	    {
	       // empty
	        
	    }
    }

    public static class NvmToHostInstructionTypeReader
    implements TypeReader
    {
	    public Object read(TypeInputStream in) throws TypeException, IOException
	    {
	        return new NvmToHostInstruction();
	    }
    }

}
